package com.fjwt.gz.task.offfline;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjwt.gz.core.aop.ScheduledLog;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.entity.OnlyOneAwardEntity;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.service.impl.OnlyOneAwardService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户奖品过期
 */
@Slf4j
@Component
public class FansCouponOffLineTask {

    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private OnlyOneAwardService onlyOneAwardService;

    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

    // 示例：正确使用方式
    @ScheduledLog(taskName = "用户奖品过期", cron = "${cron.FansCouponOffLineTask}")
//    @Scheduled(cron = "${cron.FansCouponOffLineTask}")//每3秒执行一次
    @Transactional
    public void start() {
        log.info("开始进入用户奖品过期定时任务，下线已过期的用户奖品，开始时间:{}", DateUtil.now());
        //状态  0：未使用 3：待激活
        ArrayList<Integer> stateList = new ArrayList<>();
        stateList.add(Constants.FANS_AWARD_STATE.UNUSED);
        stateList.add(Constants.FANS_AWARD_STATE.ACTIVATE);


        //查询条件：奖品类型：0卡券,1 实物 类型  状态 & 0：未使用 3：待激活  & 过期时间小于当前时间
        LambdaQueryWrapper<FansAwardEntity> gw = FansAwardEntity.gw();
        gw.in(FansAwardEntity::getAwardType, 0, 1);
        gw.in(FansAwardEntity::getState, stateList);
        gw.lt(FansAwardEntity::getOverTime, new Date());

        List<FansAwardEntity> updateList = new ArrayList<>();
        List<Long> fansAwardIds = new ArrayList<>();
        int currentPageIndex = 1; //当前页码
        while (true) {
            try {
                IPage<FansAwardEntity> fansAwardEntityIPage = fansAwardService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), gw);
                log.info("查询页数：{}，size:{}，结果list：{}", currentPageIndex, QUERY_PAGE_SIZE, JSONUtil.toJsonStr(fansAwardEntityIPage));

                if (fansAwardEntityIPage == null || fansAwardEntityIPage.getRecords().isEmpty()) { //本次查询无结果, 不再继续查询;
                    break;
                }

                for (FansAwardEntity fansAwardEntity : fansAwardEntityIPage.getRecords()) {
                    log.info("此时进行处理的信息的是：{}", JSONUtil.toJsonStr(fansAwardEntity));
                    fansAwardEntity.setState(Constants.FANS_AWARD_STATE.EXPIRED);
                    fansAwardEntity.setUpdatedAt(new Date());
                    updateList.add(fansAwardEntity);
                    JSONObject extraJson = JSONObject.parseObject(fansAwardEntity.getExtraJson());
                    String templateNo = ObjectUtils.isEmpty(extraJson) || ObjectUtils.isEmpty(extraJson.getString("templateNo"))
                            ? "" : extraJson.getString("templateNo");

                    if ("B1".equals(fansAwardEntity.getRemark())
                            || "ACTE017".equals(templateNo) || "ACTE018".equals(templateNo) || "ACTE019".equals(templateNo)) {
                        fansAwardIds.add(fansAwardEntity.getFansAwardId());
                    }
                }
                currentPageIndex++;
            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
        if (ObjectUtils.isNotEmpty(updateList)){
            fansAwardService.updateBatchById(updateList);
        }
        if (ObjectUtils.isNotEmpty(fansAwardIds)) {
            onlyOneAwardService.lambdaUpdate()
                    .in(OnlyOneAwardEntity::getFansAwardId, fansAwardIds)
                    .set(OnlyOneAwardEntity::getState, Constants.ONLY_ONE_AWARD_STATE.INVALID)
                    .update();
        }
        log.info("结束用户奖品过期定时任务，下线已过期的用户奖品，结束时间:{}", DateUtil.now());
    }
}
